<template>
    <!-- draggable：弹窗可拖动 -->
    <el-dialog v-model="dialogVisible" title="新增" width="30%" draggable @close="closeAdd(ruleFormRef)">
        <el-form :model="form" label-width="60px" ref="ruleFormRef" :rules="rules">
            <el-form-item label="书名" prop="BookName">
                <el-input v-model="form.BookName"></el-input>
            </el-form-item>
            <el-form-item label="作者" prop="Author">
                <el-input v-model="form.Author"></el-input>
            </el-form-item>
            <el-form-item label="类别" prop="TypeName">
                <el-input v-model="form.TypeName"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="Remarks">
                <el-input v-model="form.Remarks"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeAdd(ruleFormRef)">Cancel</el-button>
                <el-button type="primary" @click="save(ruleFormRef)">Confirm</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { computed, reactive, ref,watch } from 'vue';
import { FormInstance,FormRules } from 'element-plus';
import { add, edit } from '../http/index';
const props = defineProps({
    isShow:Boolean,
    info:Object
})
const dialogVisible = computed(() => props.isShow)

const form = reactive({
    Id:0,
    BookName:"",
    Author:"",
    TypeName:"",
    Remarks:""
})

// 监听
watch(() => props.info,(newInfo) => {
    if(newInfo){
        Object.assign(form,{
            Id:newInfo.id,
            BookName:newInfo.BookName,
            Author:newInfo.Author,
            TypeName:newInfo.TypeName,
            Remarks:newInfo.Remarks,
        })
    }
},{deep:true})

const ruleFormRef = reactive<FormInstance>();
const rules = reactive<FormRules>({
    BookName:[
        {required:true,message:"请输入书名",trigger:'blur'}
    ],
    Author:[
        { required:true,message:'请输入作者',trigger:"blur"}
    ],
    TypeNmme:[
        {required:true,message:"请输入类别",trigger:"blur"}
    ]
})
const emits = defineEmits(["closeAdd","success"])
const closeAdd = async (formEl:FormInstance | undefined) => {
    // if(!formEl) return
    formEl.resetFields(); // 表单重置
    emits("closeAdd");
}
const save = async (formEl:FormInstance | undefined) => {
    if(!formEl) return
    await formEl.validate((valid,fields) => {
        if(valid){
            if(form.Id){
                edit(form).then((res:any)=>{
                    if(res.data){
                        emits("success","修改成功")
                    }
                })
            }else{
                add(form).then((res:any)=>{
                    if(res.data){
                        emits("success","添加成功")
                    }
                })
            }
        }else{
            console.log('error submit',fields)
        }
    })
}
</script>